package cn.edu.zime.tjh.iotapp;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;
import java.util.List;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import android.widget.TextView;
import android.widget.Spinner;
import android.widget.ArrayAdapter;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONException;

import cn.edu.zime.tjh.iotapp.adapter.DeviceAdapter;
import cn.edu.zime.tjh.iotapp.api.ApiCallback;
import cn.edu.zime.tjh.iotapp.api.ApiService;
import cn.edu.zime.tjh.iotapp.model.Device;

public class AddEquipment extends AppCompatActivity implements DeviceAdapter.OnDeviceClickListener {

    private static final String TAG = "AddEquipment";

    // 请求码定义
    private static final int REQUEST_IMAGE_PICK = 1001;
    private static final int REQUEST_STORAGE_PERMISSION = 1002;

    // 视图组件
    private RecyclerView recyclerDevices;
    private TextView textEmpty;
    private SwipeRefreshLayout swipeRefresh;
    private DeviceAdapter deviceAdapter;
    private List<Device> deviceList;
    private ApiService apiService;

    private Bitmap qrCodeBitmap;
    private Spinner spinnerDeviceTypes;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.addequipments);
        
        // 初始化UI组件
        recyclerDevices = findViewById(R.id.recyclerDevices);
        textEmpty = findViewById(R.id.textEmpty);
        swipeRefresh = findViewById(R.id.swipeRefresh);
        
        // 初始化API服务
        apiService = new ApiService();
        
        // 初始化设备列表
        deviceList = new ArrayList<>();
        deviceAdapter = new DeviceAdapter(this, deviceList, this);
        
        // 设置RecyclerView
        recyclerDevices.setLayoutManager(new LinearLayoutManager(this));
        recyclerDevices.setAdapter(deviceAdapter);
        
        // 设置下拉刷新
        swipeRefresh.setColorSchemeResources(R.color.status_online);
        swipeRefresh.setOnRefreshListener(this::loadDevices);
        
        // 加载设备列表
        loadDevices();
    }

    // 加载设备列表数据的方法
    private void loadDevices() {
        swipeRefresh.setRefreshing(true);
        
        apiService.getDeviceList(new ApiCallback() {
            @Override
            public void onSuccess(JSONObject response) {
                try {
                    int code = response.getInt("code");
                    if (code == 200) {
                        JSONArray deviceArray = response.getJSONArray("data");
                        List<Device> devices = new ArrayList<>();
                        
                        for (int i = 0; i < deviceArray.length(); i++) {
                            JSONObject deviceObj = deviceArray.getJSONObject(i);
                            
                            // 获取设备信息，同时处理不同的字段名
                            String deviceId = deviceObj.has("device_id") ? deviceObj.getString("device_id") : 
                                              (deviceObj.has("id") ? deviceObj.getString("id") : "");
                                              
                            String deviceName = deviceObj.has("device_name") ? deviceObj.getString("device_name") : 
                                                (deviceObj.has("name") ? deviceObj.getString("name") : "");
                                                
                            String deviceType = deviceObj.has("device_type") ? deviceObj.getString("device_type") : 
                                                (deviceObj.has("type") ? deviceObj.getString("type") : "");
                                                
                            String deviceStatus = deviceObj.has("device_status") ? deviceObj.getString("device_status") : 
                                                  (deviceObj.has("status") ? deviceObj.getString("status") : "active");
                            
                            // 使用2个参数的构造函数
                            Device device = new Device(deviceId, deviceName);
                            device.setDeviceType(deviceType);
                            device.setDeviceStatus(deviceStatus);
                            
                            // 设置可选字段
                            if (deviceObj.has("device_info") && !deviceObj.isNull("device_info")) {
                                device.setDeviceInfo(deviceObj.getString("device_info"));
                            }
                            
                            if (deviceObj.has("device_web") && !deviceObj.isNull("device_web")) {
                                device.setDeviceWeb(deviceObj.getString("device_web"));
                            }

                            devices.add(device);
                        }
                        
                        deviceList.clear();
                        deviceList.addAll(devices);
                        
                        runOnUiThread(() -> {
                            deviceAdapter.notifyDataSetChanged();
                            swipeRefresh.setRefreshing(false);
                            
                            // 更新空视图状态
                            if (deviceList.isEmpty()) {
                                textEmpty.setVisibility(View.VISIBLE);
                                recyclerDevices.setVisibility(View.GONE);
                            } else {
                                textEmpty.setVisibility(View.GONE);
                                recyclerDevices.setVisibility(View.VISIBLE);
                            }
                        });
                    } else {
                        String message = response.optString("message", "加载设备列表失败");
                        throw new Exception(message);
                    }
                } catch (Exception e) {
                    Log.e(TAG, "解析设备列表失败: " + e.getMessage());
                    runOnUiThread(() -> {
                        Toast.makeText(AddEquipment.this, "加载设备列表失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                        swipeRefresh.setRefreshing(false);
                    });
                }
            }
            
            @Override
            public void onFailure(String errorMsg) {
                Log.e(TAG, "加载设备列表失败: " + errorMsg);
                runOnUiThread(() -> {
                    Toast.makeText(AddEquipment.this, "加载设备列表失败: " + errorMsg, Toast.LENGTH_SHORT).show();
                    swipeRefresh.setRefreshing(false);
                });
            }
        });
    }

    // 显示添加设备对话框
    public void showAddDialog(View view) {
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_add_device, null);
        
        // 初始化所有UI组件
        EditText editDeviceName = dialogView.findViewById(R.id.editDeviceName);
        EditText editDeviceInfo = dialogView.findViewById(R.id.editDeviceInfo);
        EditText editDeviceWeb = dialogView.findViewById(R.id.editDeviceWeb);
        spinnerDeviceTypes = dialogView.findViewById(R.id.spinnerDeviceTypes);
        Spinner spinnerDeviceStatus = dialogView.findViewById(R.id.spinnerDeviceStatus);
        
        // 设置设备类型下拉列表
        String[] deviceTypes = {"temperature", "humidity", "light", "camera", "gateway", "sensor", "controller", "general", "other"};
        ArrayAdapter<String> typeAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, deviceTypes);
        spinnerDeviceTypes.setAdapter(typeAdapter);
        
        // 设置设备状态下拉列表
        String[] deviceStatus = {"active", "inactive", "maintenance", "error"};
        ArrayAdapter<String> statusAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, deviceStatus);
        spinnerDeviceStatus.setAdapter(statusAdapter);
        
        // 默认选择"active"状态
        spinnerDeviceStatus.setSelection(0);
        

        
        AlertDialog dialog = new AlertDialog.Builder(this)
            .setTitle("添加设备")
            .setView(dialogView)
            .setPositiveButton("添加", (dialogInterface, i) -> {
                // 获取用户输入
                String deviceName = editDeviceName.getText().toString().trim();
                String deviceType = spinnerDeviceTypes.getSelectedItem().toString();
                String deviceInfo = editDeviceInfo.getText().toString().trim();
                String deviceWeb = editDeviceWeb.getText().toString().trim();
                String status = spinnerDeviceStatus.getSelectedItem().toString();
                
                // 使用随机码作为设备ID
                String randomCode = "DEV" + (1000 + (int)(Math.random() * 9000));
                
                // 构建设备信息JSON
                JSONObject deviceInfoJson = new JSONObject();
                try {
                    deviceInfoJson.put("model", "IoT Demo Device");
                    deviceInfoJson.put("firmware", "v1.0");
                    // ... 其他信息 ...
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                
                // 调用添加设备API
                apiService.addDevice(
                    randomCode,           // device_id
                    deviceName,           // device_name
                    deviceType,           // device_type 
                    deviceInfo,           // device_info
                    deviceWeb,            // device_web
                    null,                 // image (添加null参数)
                    status,               // device_status
                    new ApiCallback() {
                        @Override
                        public void onSuccess(JSONObject response) {
                            processAddDeviceResponse(response, randomCode, deviceName, 
                                                   deviceType, deviceInfo, deviceWeb, status);
                        }
                        
                        @Override
                        public void onFailure(String errorMsg) {
                            Log.e(TAG, "添加设备失败: " + errorMsg);
                            runOnUiThread(() -> {
                                Toast.makeText(AddEquipment.this, "添加设备失败: " + errorMsg, 
                                             Toast.LENGTH_SHORT).show();
                            });
                        }
                    }
                );
                
                // 重置二维码
                qrCodeBitmap = null;
            })
            .setNegativeButton("取消", null)
            .create();
        
        dialog.show();
    }

    // 处理添加设备响应
    private void processAddDeviceResponse(JSONObject response, String deviceId, String deviceName,
                                        String deviceType, String deviceInfo, String deviceWeb,
                                        String status) {
        try {
            int code = response.getInt("code");
            if (code == 200 || code == 201) {
                JSONObject deviceData = response.getJSONObject("data");
                
                // 从响应中获取设备ID (可能是服务器生成的新ID)
                String newDeviceId = deviceData.has("device_id") ? 
                    deviceData.getString("device_id") : 
                    (deviceData.has("id") ? deviceData.getString("id") : deviceId);
                
                // 创建设备对象 - 使用二参数构造函数
                Device newDevice = new Device(newDeviceId, deviceName);
                // 恢复这些设置
                newDevice.setDeviceType(deviceType);
                newDevice.setDeviceStatus(status);
                
                // 设置可选属性
                if (deviceInfo != null && !deviceInfo.isEmpty()) {
                    newDevice.setDeviceInfo(deviceInfo);
                }
                
                if (deviceWeb != null && !deviceWeb.isEmpty()) {
                    newDevice.setDeviceWeb(deviceWeb);
                }
                
                // 更新UI
                runOnUiThread(() -> {
                    deviceAdapter.addDevice(newDevice);
                    
                    if (deviceList.isEmpty()) {
                        textEmpty.setVisibility(View.GONE);
                        recyclerDevices.setVisibility(View.VISIBLE);
                    }
                    
                    Toast.makeText(AddEquipment.this, "设备添加成功", Toast.LENGTH_SHORT).show();

                });
            } else {
                String message = response.optString("message", "添加设备失败");
                throw new Exception(message);
            }
        } catch (Exception e) {
            Log.e(TAG, "解析添加设备响应失败: " + e.getMessage());
            runOnUiThread(() -> {
                Toast.makeText(AddEquipment.this, "处理响应失败: " + e.getMessage(), 
                             Toast.LENGTH_SHORT).show();
            });
        }
    }

    // 删除设备
    private void deleteDevice(String deviceId, int position) {
        apiService.deleteDevice(deviceId, new ApiCallback() {
            @Override
            public void onSuccess(JSONObject response) {
                runOnUiThread(() -> {
                    deviceAdapter.removeDevice(position);
                    
                    if (deviceList.isEmpty()) {
                        textEmpty.setVisibility(View.VISIBLE);
                        recyclerDevices.setVisibility(View.GONE);
                    }
                    
                    Toast.makeText(AddEquipment.this, "设备已删除", Toast.LENGTH_SHORT).show();
                });
            }
            
            @Override
            public void onFailure(String errorMsg) {
                Log.e(TAG, "删除设备失败: " + errorMsg);
                runOnUiThread(() -> {
                    Toast.makeText(AddEquipment.this, "删除设备失败: " + errorMsg, Toast.LENGTH_SHORT).show();
                });
            }
        });
    }

    // 返回按钮点击事件处理
    public void EqBack(View view) {
        finish();
    }
    
    // DeviceAdapter.OnDeviceClickListener 接口实现
    @Override
    public void onDeviceClick(Device device) {
        // 跳转到设备详情页面
        Intent intent = new Intent(this, DeviceDetailActivity.class);
        intent.putExtra("DEVICE_ID", device.getDeviceId());
        intent.putExtra("DEVICE_NAME", device.getDeviceName());
        intent.putExtra("DEVICE_TYPE", device.getDeviceType());
        startActivity(intent);
    }
    
    @Override
    public void onDeviceLongClick(Device device, int position) {
        // 显示删除确认对话框
        new AlertDialog.Builder(this)
            .setTitle("删除设备")
            .setMessage("确定要删除设备 " + device.getDeviceName() + " 吗？")
            .setPositiveButton("删除", (dialog, which) -> {
                deleteDevice(device.getDeviceId(), position);
            })
            .setNegativeButton("取消", null)
            .show();
    }
}